package com.situ.stl.interceptor;

import com.situ.stl.entity.Admin;
import com.situ.stl.entity.Result;
import com.situ.stl.service.AdminService;
import com.situ.stl.util.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.Console;

/** 
 * 用户登录拦截器
 */
@Component
@Slf4j
public class AdminInterceptor implements HandlerInterceptor{

    @Autowired
    private AdminService adminService;

    /** 
     * 拦截未登录用户
     */
    @Override 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  throws Exception{
        // 读取请求头中的Token
        String token = request.getHeader("token");

        String uri = request.getRequestURI();
        System.out.println("Admin拦截器" + uri);

        // 当前登录用户
        Admin admin = null;
        // 有Token, 解析
        if ( StringUtils.hasText(token)) {
            // 尝试解析
            try {
                Claims claims = JWTUtil.parseJWT(token);
                String phone = claims.getSubject();
                admin = adminService.getByPhone(phone);
            } catch (Exception e) {
                log.info("无效的token");
            }
        }

        if (admin != null) {
            // 刷新Token
            String newToken = JWTUtil.createJWT(admin.getPhone());
            System.out.println(newToken);
            response.setHeader("token", newToken);

        	return true;
        } else {
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(Result.error("当前用户未登录或登录已过期！").toJson());
        	return false;
        }
    }

}